<?php

namespace App\Admin\Controllers;

use App\AdminUser;
use Illuminate\Http\Request;

class UserController extends Controller
{
    //
    public function index()
    {
        $users = AdminUser::OrderBy('created_at', 'desc')->paginate(10);
        return view('admin.user.index', compact('users'));
    }

    public function create()
    {
        return view('admin.user.add');
    }

    public function store()
    {
        $this->validate(\request(), [
            'name' => 'required | | unique:admin_users,name',
            'password' => 'required | min:6 | max:18 | confirmed'
        ]);

        //逻辑
        $name = \request('name');
        $password = bcrypt(\request('password'));
        $user = AdminUser::create(compact('name', 'password'));

        //渲染
        return redirect('/admin/users');
    }

    //角色管理列表
    public function role(AdminUser $user)
    {
        $roles = \App\AdminRole::all();
        $myRoles = $user->roles;
        return view('admin.user.role', compact('roles', 'myRoles', 'user'));
    }

    //保存角色
    public function storeRole(AdminUser $user)
    {
        $this->validate(\request(), [
            'roles' => 'required | array'
        ]);

        //所有选择的权限
        $roles = \App\AdminRole::findMany(\request('roles'));
        //原有的权限
        $myRoles = $user->roles;

        //要增加的
        $addRoles = $roles->diff($myRoles);
        foreach($addRoles as $role) {
            $user->assignRole($role);
        }

        //要删除的
        $deleteRoles = $myRoles->diff($roles);
        foreach($deleteRoles as $role) {
            $user->deleteRole($role);
        }

        return back();
    }
}
